<script setup>
import { insertNewFaculties } from '@/api/admin/faculties.js'
import { ref, defineProps, defineEmits, computed } from 'vue'
import { ElNotification } from 'element-plus'

// 组合api中导入的数据如果不需要响应式，无需再次定义变量，本身已经是变量了
import rules from '@/rules/depart.js'

let props = defineProps(['modelValue'])
let emit = defineEmits(['update:modelValue', 'reset'])

// let rules = ref({
//   department_name: [{ required: true, message: '院系名称不能为空', trigger: 'blur' }],
// })
// let rules = {
//   department_name: [{ required: true, message: '院系名称不能为空', trigger: 'blur' }],
// }

let flag = computed({
  get() {
    return props.modelValue
  },
  set(nv) {
    // console.log(nv)
    emit('update:modelValue', nv)
  },
})

let params = ref({
  department_name: '',
})
// ref除了可以定义响应式数据外，也会自动从页面中获取和变量名一样的 DOM对象或者组件实例
let addForm = ref(null)
const addNewDepart = async function () {
  // 判断一下数据是否合法
  //    通过ref获取ElForm实例对象，使用组件公开的内置校验方法
  //      如果表单中的所有输入数据都合法 返回 成功 promise
  //      如果表单中的有一个输入数据都不合法 返回 失败 promise
  await addForm.value.validate()
  await insertNewFaculties(params.value)
  // 导入 ElNotification
  ElNotification.success({
    title: `“${params.value.department_name}”添加成功`,
  })
  emit('reset')
  params.value = {
    department_name: '',
  }
  console.log(flag)

  flag.value = false
}

const clearDialog = function () {
  // 数据清空
  params.value = {
    department_name: '',
  }
  // 校验清空
  addForm.value.clearValidate()
}
</script>

<template>
  <el-dialog v-bind="$attrs" v-model="flag" @close="clearDialog">
    <template #header>
      <span>新院系添加</span>
    </template>

    <el-form
      class="form"
      label-width="80px"
      :inline="false"
      :rules="rules"
      :model="params"
      ref="addForm"
    >
      <el-form-item label="院系名:" prop="department_name">
        <el-input v-model="params.department_name"></el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="flag = false">取消</el-button>
        <el-button type="primary" @click="addNewDepart()">添加</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.form {
  padding: 20px 40px;
}
.time-row {
  display: flex;
  flex-flow: row nowrap;
  width: 100%;
}
.time-row .el-select {
  flex-grow: 1;
}
:deep(.el-date-editor) {
  width: 100%;
}
</style>
